package com.bart.scala.ch16.httpclient;

import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.serializer.SerializerFeature
import org.apache.http.client.methods.{HttpGet, HttpPost}
import org.apache.http.entity.StringEntity
import org.apache.http.impl.client.HttpClients
import org.apache.http.util.EntityUtils


/**
  * Created by zhoujiamu on 2019/1/9.
  */
object MyHttpResponse {

  def getResponse(url: String, header: String = null): String = {
    val httpClient = HttpClients.createDefault()    // 创建 client 实例
    val get = new HttpGet(url)    // 创建 get 实例

    if (header != null) {   // 设置 header
      val json = JSON.parseObject(header)
      json.keySet().toArray.map(_.toString).foreach(key => get.setHeader(key, json.getString(key)))
    }

    val response = httpClient.execute(get)    // 发送请求
    EntityUtils.toString(response.getEntity)    // 获取返回结果
  }

  def postResponse(url: String, params: String = null, header: String = null): String ={
    val httpClient = HttpClients.createDefault()    // 创建 client 实例
    val post = new HttpPost(url)    // 创建 post 实例

    // 设置 header
    if (header != null) {
      val json = JSON.parseObject(header)
      json.keySet().toArray.map(_.toString).foreach(key => post.setHeader(key, json.getString(key)))
    }

    if (params != null) {
      post.setEntity(new StringEntity(params, "UTF-8"))
    }

    val response = httpClient.execute(post)    // 创建 client 实例
    EntityUtils.toString(response.getEntity, "UTF-8")   // 获取返回结果
  }


  def main(args: Array[String]): Unit = {

    // 1） get请求
//    val url = "http://192.168.1.00:8082/risk/getUserByGet?userName=zhoujiamu"
//    println("This get response: ")
//    println(getResponse(url))

    // 1） post请求
//    val postUrl = "http://192.168.1.00:8082/risk/group"
//    val params = """{"company_list":["北京佛尔斯特金融信息服务有限公司"],"conditions":{}}"""
//
//    println("This post response: ")
//    println(postResponse(postUrl, params, """{"Content-Type": "application/json"}"""))
//    val header =
//        """
//        |{
//        |    "Accept": "application/json;charset=UTF-8",
//        |    "Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept",
//        |    "Connection": "keep-alive",
//        |    "Content-Type": "application/json; charset=utf-8",
//        |    "Authorization": "Bearer eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiI1TVAwU0w4TmVnciIsImV4cCI6MTU5NTU0NzE4MSwidWlkIjozMDR9.uf8VTB4yWh2nl2SmL8GJmDa6zewhMZF2QMh6SIcKFR4"
//        |}
//      """.stripMargin
//
//     // 需要token认证的情况，在header中加入Authorization
//     println(postResponse(postUrl, params, header))

    // 3）post请求 2
    val postUrl2 = "http://localhost:9191/api/cmp-analysis-alarm/alarmPut?methodName=saveAlarm"
    val mapParam = new scala.collection.mutable.HashMap[String,  Any]()
    mapParam.put("sid", "12312321")
    mapParam.put("salary", 12568.12)
    mapParam.put("num", 10000L)
    mapParam.put("finish", true)
    import scala.collection.JavaConverters._
    val javaMap = mapParam.asJava
//    val params2 = JSON.toJSONString(javaMap) // 会报错scala无法确定重载的是哪一个方法
    val params2 = JSON.toJSONString(javaMap, SerializerFeature.QuoteFieldNames)
    println(params2)// {"finish":true,"num":10000,"salary":12568.12,"sid":"12312321"}
    val header2 =
            """
            |{
            |    "Accept": "application/json;charset=UTF-8",
            |    "Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept",
            |    "Connection": "keep-alive",
            |    "Content-Type": "application/json; charset=utf-8",
            |    "thirdCode": "alarm",
            |    "sign": "saYjJlxx",
            |}
          """.stripMargin
    println(postResponse(postUrl2, params2, header2))
    // saveAlarm{finish=true, num=10000, salary=12568.12, sid=12312321}1610515341548
  }

}
